package com.sunnada.edu.system.pub.controller;

import java.io.File;
import java.io.FileInputStream;
import java.io.IOException;
import java.io.OutputStream;
import java.util.HashMap;
import java.util.Map;

import javax.annotation.Resource;
import javax.servlet.ServletContext;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;

import org.apache.commons.io.IOUtils;
import org.springframework.stereotype.Controller;
import org.springframework.web.bind.annotation.RequestMapping;

import com.alibaba.fastjson.JSONObject;
import com.sunnada.edu.system.login.service.LoginMethods;
import com.sunnada.edu.system.login.service.LoginService;
import com.sunnada.edu.system.pub.cache.ConfigCache;
import com.sunnada.edu.system.pub.common.BasicController;
import com.sunnada.edu.system.pub.common.Common;
import com.sunnada.edu.system.pub.common.Constants;
import com.sunnada.edu.system.pub.common.MD5;
import com.sunnada.edu.system.pub.common.RandomTool;
import com.sunnada.edu.system.pub.service.PubMethods;
import com.sunnada.edu.system.pub.service.PubService;
import com.sunnada.edu.system.pub.util.Utils;

@Controller
@RequestMapping("/pubController")
public class PubController extends BasicController {
	@Resource
	PubService pubService;
	@Resource
	LoginService loginService;

	/** 1.忘记密码页面 */
	@RequestMapping("/forgetPwdPage")
	public String forgetPwdPage(HttpServletRequest request) {
		String userId = request.getParameter("userId");
		request.setAttribute("userId", userId);
		return "system/common/forgetPwd";
	}

	/** 1.判断客户是否可以获取短信验证码 */
	@RequestMapping("/getForgetMsg")
	public void getForgetMsg(HttpServletRequest request,
			HttpServletResponse response) {
		String userId = request.getParameter("userId");
		userId = Utils.devExceptString(userId); // 去掉非法字符
		HashMap<String, String> params = new HashMap<String, String>();
		params.put("userId", userId);
		String msg = pubService.getForgetMsgState(params);
		printInfo(response, msg);
	}

	/**
	 * 2. 忘记密码： 输入忘记密码的短信验证码界面
	 * */
	@RequestMapping("/pubForgetsCks")
	public String clientForgetsCks(HttpServletRequest request,
			HttpServletResponse response) {
		request.setAttribute("userId", request.getParameter("userId"));
		String pageLabel = RandomTool.randString(16);
		request.getSession().setAttribute(pageLabel, "0");
		String desRandom = RandomTool.randNum(16); // 用于生成密钥的随机数
		request.getSession().setAttribute(Constants.DESSTRING, desRandom);
		request.getSession().setAttribute("desRandom", desRandom);
		request.getSession().setAttribute("pageLabel", pageLabel);
		return "system/common/forgetCks";
	}

	/**
	 * 2. 忘记密码： 获取短信验证码
	 * */
	@RequestMapping("/pubgetSMsg")
	public void pubgetSMsg(HttpServletRequest request,
			HttpServletResponse response) {
		String userId = request.getParameter("userId");
		userId = Utils.devExceptString(userId); // 去掉非法字符
		HashMap<String, String> params = new HashMap<String, String>();
		params.put("userId", userId);
		String msg = pubService.pubgetSMsg(params);
		printInfo(response, msg);
	}

	/**
	 * 忘记密码：短信验证码验证
	 * */
	@RequestMapping("/forgetsLogin")
	public void forgetsLogin(HttpServletRequest request,
			HttpServletResponse response) {
		String msg = pubService.clientForgetsLogin(request);
		printInfo(response, msg);
	}

	/** 修改密码页面 */
	@RequestMapping("/updatePwdPage")
	public String updatePwdPage(HttpServletRequest request) {
		String userId = request.getParameter("userId");
		request.setAttribute("userId", userId);
		return "system/common/pwd_update";
	}

	/**
	 * 修改密码
	 * 
	 * @param request
	 * @param response
	 */
	@RequestMapping("/pwdUpdate")
	public void pwdUpdate(HttpServletRequest request,
			HttpServletResponse response) {
		JSONObject returnJson = new JSONObject();
		HashMap<String, String> params = new HashMap<String, String>();
		String userId = (String) request.getSession().getAttribute("USER_LOGINCODE");
		params.put("userId", userId);
		String oldpassword = request.getParameter("oldpassword");
		String newpassword = request.getParameter("newpassword");
		String againpassword = request.getParameter("againpassword");
		String msg = "";

		// String key=(String)
		// request.getSession().getAttribute(Constants.DESSTRING); //密钥
		// newpassword= DESJAVA.strDec(newpassword, key,null,null);

		// 验证旧密码
		String oldPwd = MD5.md5(userId + oldpassword);
		String password = MD5.md5(userId + newpassword);

		params.put("password", oldPwd);
		Map userMap = loginService.getUserByUserId(params);
		if (null == userMap) {
			msg = "原始密码错误，请重新确认！";
			returnJson.put("msg", msg);
			returnJson.put("success", false);
			printInfo(response, returnJson);
			return;
		}

		params.put("password", password);
		int num = LoginMethods.updatePwd(params);
		if (num > 0) {
			msg = "密码修改成功！";
			returnJson.put("success", true);
		} else {
			msg = "密码修改失败，请联系管理员！";
			returnJson.put("success", false);
		}
		returnJson.put("msg", msg);
		printInfo(response, returnJson);
	}

	@RequestMapping("/checkClientKey")
	public void checkClientKey(HttpServletRequest request,
			HttpServletResponse response) {
		String clientKey = request.getParameter("clientKey");

	}

	@RequestMapping("/getKey")
	public void getKey(HttpServletRequest request, HttpServletResponse response)
			throws IOException {
		String clientkey = request.getParameter("desRandom"); // 前端的随机数
		String backstagekey = (String) request.getSession().getAttribute(
				Constants.DESRANDOMSTRING); // 后台保存的随机数
		if (Utils.isNotNull(clientkey) && Utils.isNotNull(backstagekey)
				&& clientkey.equals(backstagekey)) {
			System.out.println("clientkey:" + clientkey + "backstagekey"
					+ backstagekey);
			String productkey = RandomTool.productKey(backstagekey, 16);
			request.getSession().setAttribute(Constants.DESSTRING, productkey);
			printInfo(response, productkey);
		} else {
			printInfo(response, "密钥生成数据出错,请重新提交或者关闭程序重新运行！");
		}
	}

	/**
	 * 通用版：根据文件路径和文件名，下载文件
	 * @param request path+fileName
	 * @param response
	 * @throws IOException
	 */
	@RequestMapping("downloadFile")
	public void downloadFile(HttpServletRequest request,
			HttpServletResponse response) throws IOException {
		HashMap<String, String> params = new HashMap<String, String>();
		setReqParams(request, null, params);
		String realPath = request.getSession().getServletContext()
				.getRealPath("/");
		String path = realPath + params.get("path");
		String fileName = params.get("fileName");
		File file = new File(path);
		ServletContext context = request.getSession().getServletContext();
		if (file.isFile()) {
			String mimeType = context.getMimeType(path); // 直接根据文件的路径名来获取它的MineType，这样就可以灵活的根据请求的文件类型来返回输出流了
			response.setContentType(mimeType);
			response.addHeader("Content-Disposition", "attachment; filename="
					+ new String(fileName.getBytes("UTF-8"),"iso-8859-1"));//下载时防止不识别中文文件名
			try {
				OutputStream os = response.getOutputStream();
				IOUtils.copy(new FileInputStream(file), os);
				os.flush();
			} catch (IOException ex) {
				ex.printStackTrace();
			}
		}
	}
	
	
	
	/**
	 * 拼接区域json数据
	 * @param request
	 * @param response
	 */
	@RequestMapping("/getAreaPanel")
	public void getAreaPanel(HttpServletRequest request,
			HttpServletResponse response) {
		JSONObject returnJson = new JSONObject();
		Map map=(Map)ConfigCache.getAreaPanel();
		returnJson.put("area", map);
		printInfo(response, returnJson);
	}

}
